# !/usr/bin/env python3
# -*- coding: utf-8 -*-
###----------------------------------------------------1、文件说明----------------------------------------------------###
'''
* 说明：操作xml的库的学习笔记
* 时间：2021-1-18
* 文件：
* 作者：whg
* 备注：
'''
###----------------------------------------------------2、库导入----------------------------------------------------###
try:
    import xml.etree.cElementTree as ET  #C语言的实现
except ImportError:
    import xml.etree.ElementTree as ET  #纯Python的实现
import xml.dom.minidom as DOM
import lxml
###----------------------------------------------------3、参数配置----------------------------------------------------###
###----------------------------------------------------4、主体程序----------------------------------------------------###

class WXml(object):
    '''
    操作xml的类
    '''
    def __init__(self, filename):
        self.filename = filename

    def ReadFile(self, filename):
        '''
        从xml文件中读取
        :param filename: 文件的绝对路径
        :return:
        '''
        tree = ET.parse(filename)
        self.root = tree.getroot()

    def ReadStr(self, string):
        '''
        从字符串中读取
        :param string: xml字符串
        :return:
        '''
        self.root = ET.fromstring(string)

    def GetRoot(self):
        '''
        获取解析后的根结点
        :return:
        '''
        return self.root

    def XPath(self, string):
        '''
        使用XPath语法进行查找
        :param string:
        :return:
        '''
        return self.root.findall(string)

    def ToString(self):
        self.string = ET.tostring(self.root)
        return self.string

    def WriteFile(self, outfile):
        '''
        将xml写入到文件中
        :return:
        '''
        xml_write = DOM.parseString(self.string)
        with open(outfile, 'w') as handle:
            xml_write.writexml(handle, indent='', newl='', encoding='utf-8')

if __name__ == '__main__':
    print('Start Program...\r\n')
    with open("demo.xml", "r") as file:
        string = file.read()
    xml = wxml("name")
    # xml.ReadFile("demo.xml")
    xml.ReadStr(string)
    out = xml.ToString()
    print(out)
    xml.WriteFile("outfile.xml")
    print(xml.XPath("./country/neighbor"))
    print('\nSuccess ...')